import { ArticleComment, ArticleDetail } from '@/types/data'
import { ArticleAction } from '@/types/store'

type ArticleState = {
  detail: ArticleDetail
  comments: ArticleComment
}
const initialState = {
  detail: {},
  comments: {
    end_id: null,
    last_id: '',
    total_count: 0,
    results: [] as ArticleComment['results'],
  },
} as ArticleState

export const article = (
  state = initialState,
  action: ArticleAction
): ArticleState => {
  if (action.type === 'article/get') {
    return { ...state, detail: action.payload }
  }
  if (action.type === 'article/update') {
    const { name, value } = action.payload
    return {
      ...state,
      detail: { ...state.detail, [name]: value },
    }
  }
  //获取评论数据
  if (action.type === 'article/getArticleComments') {
    const { end_id, last_id, results, total_count } = action.payload
    return {
      ...state,
      comments: {
        end_id,
        last_id,
        total_count,
        results: [...state.comments.results, ...results],
      },
    }
  }
  if (action.type === 'article/getArticleCommentsFirst') {
    return {
      ...state,
      comments: action.payload,
    }
  }
  //添加
  if (action.type === 'article/addArticleComment') {
    return {
      ...state,
      comments: {
        ...state.comments,
        results: [action.payload, ...state.comments.results],
      },
    }
  }
  //给评论点赞
  if (action.type === 'artilce/articleCommentThumbUp') {
    const { id, is_liking } = action.payload
    return {
      ...state,
      comments: {
        ...state.comments,
        results: state.comments.results.map((item) => {
          if (item.com_id === id) {
            return {
              ...item,
              is_liking: is_liking,
              like_count: is_liking ? item.like_count + 1 : item.like_count - 1,
            }
          }
          return item
        }),
      },
    }
  }
  return state
}
